package cn.gov.pbc.gd.credit.web.servlet;

import java.io.File;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.liu.tools.FileListenerUtil;
import com.liu.tools.conf.ConfigurerEx;
import com.liu.tools.conf.LocalConfig;
import com.liu.tools.conf.LogBackConfigLoader;

public class InitServlet extends HttpServlet{

	private static final long serialVersionUID = -8821462143809798199L;
	
	private static Logger logger = LoggerFactory.getLogger(InitServlet.class);
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		autoReloadConf();
	
		haha();


	}
	
	private void haha(){
		
		new Thread(
				new Runnable() {
					
					@Override
					public void run() {
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						StringBuffer sb = new StringBuffer();
						System.out.println("  ");
						System.out.println("**************************************************************************");
				        sb.append("                   _ooOoo_\n");
				        sb.append("                  o8888888o\n");
				        sb.append("                  88\" . \"88\n");
				        sb.append("                  (| -_- |)\n");
				        sb.append("                  O\\  =  /O\n");
				        sb.append("               ____/`---'\\____\n");
				        sb.append("             .'  \\\\|     |//  `.\n");
				        sb.append("            /  \\\\|||  :  |||//  \\ \n");
				        sb.append("           /  _||||| -:- |||||-  \\ \n");
				        sb.append("           |   | \\\\\\  -  /// |   |\n");
				        sb.append("           | \\_|  ''\\---/''  |   |\n");
				        sb.append("           \\  .-\\__  `-`  ___/-. /\n");
				        sb.append("         ___`. .'  /--.--\\  `. . __\n");
				        sb.append("      .\"\" '<  `.___\\_<|>_/___.'  >'\"\".\n");
				        sb.append("     | | :  `- \\`.;`\\ _ /`;.`/ - ` : | |\n");
				        sb.append("     \\  \\ `-.   \\_ __\\ /__ _/   .-` /  /\n");
				        sb.append("======`-.____`-.___\\_____/___.-`____.-'======\n");
				        sb.append("                   `=---='\n");
				        sb.append("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
				        sb.append("\t 佛祖保佑       永无BUG\n");
				        sb.append("佛曰：\n");
				        sb.append("\t写字楼里写字间，写字间里程序员； \n");
				        sb.append("\t程序人员写程序，又拿程序换酒钱。\n");   
				        sb.append("\t酒醒只在网上坐，酒醉还来网下眠；\n");   
				        sb.append("\t酒醉酒醒日复日，网上网下年复年。\n");   
				        sb.append("\t但愿老死电脑间，不愿鞠躬老板前；\n");   
				        sb.append("\t奔驰宝马贵者趣，公交自行程序员。\n");   
				        sb.append("\t别人笑我忒疯癫，我笑自己命太贱；\n");   
				        sb.append("\t不见满街漂亮妹，哪个归得程序员？\n");
				        System.out.println(sb.toString());
				        System.out.println("**************************************************************************");
						
					}
				}
		).start();
		
		
        
	}
	
	private void autoReloadConf() {

		logger.info("atuo:reloadConf", "S_OK", "启动自动刷新配置, 监控目录："	+ LocalConfig.configPath);

		try {

			FileListenerUtil.runFileListenter(
					new FileAlterationListenerAdaptor() {
						/**
						 * 文件创建修改
						 */
						@Override
						public void onFileChange(File file) {

							long l = System.currentTimeMillis();
							String name = file.getName();

							try {

								if ("logback.xml".equalsIgnoreCase(name)) {
									
									logger.info("atuo:reloadConf", "S_OK", "File " + name + " is update!");
									LogBackConfigLoader.load(getServletContext());
									logger.info("atuo:reloadConf","S_OK",name + " reload is ok. time="	+ (System.currentTimeMillis() - l)+ " ms");
								} else if (name.endsWith("conf")) {

									
									ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

									ConfigurerEx propertiesUtil = (ConfigurerEx) ctx.getBean("placeholderConfig");
									propertiesUtil.loadProperties(propertiesUtil.getProps());
									propertiesUtil.processProperties(propertiesUtil.getBeanFactory(), propertiesUtil.getProps());
									
									//Conf.reload();
									
									logger.info("atuo:reloadConf","S_OK", name + " reload is ok. time="	+ (System.currentTimeMillis() - l)	+ " ms");		
								}

							} catch (Exception e) {
								logger.error("atuo:reloadConf", "S_FAIL", name + "文件自动刷新失败！", e);
							}

						}

					}, LocalConfig.configPath);

			logger.info("atuo:reloadConf", "S_OK", "自动刷新配置启动成功...........");
		} catch (Exception e) {
			logger.error("atuo:reloadConf", "S_FAIL", "自动刷新配置启动失败...........", e);
		}

	}
}
